import Event from './event';
import ITool from '../ITool';

// import SnapUtil from '../../utils/SnapUtil';
import SplitUtil from '../../utils/SplitUtil';
import AdvancedSnapUtil from '../../utils/AdvancedSnapUtil';
import SliceUtil2 from '../../utils/SliceUtil2';

/**
 * 编辑工具箱
 * @implements {ITool}
 */
class EditTool extends ITool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'EditTool';
    this.desc = '编辑工具箱';
    this._tool = null;
    this.snapUtil = null;
    this.events = {
      onCreate: null,
      onDelete: null,
      onUpdate: null,
      onDragmove: null,
      onSelectionchange: null,
      onModechange: null,
      onActionable: null,
      onRender: null,
      onCombine: null,
      onUncombine: null,
      onDragVertex: null,
      onUnion: null,
      onKeyDown: null
    };
    this._defaultSnapFunction = this.defaultSnapFunction.bind(this);
  }

  onAdd() {
    super.onAdd();
    // 初始化绑定事件
    this.eventTool = new Event(this);
    // 初始化捕捉工具箱
    // this.snapUtil = new SnapUtil(this.getMap());
    // 高级捕捉工具
    this.snapUtil = new AdvancedSnapUtil(this.getMap());
    this.splitUtil = new SplitUtil(this);
    // 初始化工具
    this.initTool();
  }

  onRemove() {
    super.onRemove();
    this.eventTool.removeEvents();
  }

  /**
   * 初始化工具
   */
  initTool() {
    if (this._tool) {
      this.moveGlDrawLayersToTop();
      this.log('draw tool already init, skipped');
      return;
    }
    this._tool = new FZGISDraw({
      displayControlsDefault: false,
      // 通过该属性，设置绘制带有pattern属性的线、点
      symbolProperties: true,
      // 捕捉设置
      snap: false,
      snapOptions: {
        snapPx: 15, // defaults to 5
        snapToMidPoints: true // defaults to false
      },
      sliceOptions: {
        sliceFunction: null
      },
      // 平行线捕捉设置
      parallel: true,
      parallelOptions: { snapPx: 15 },
      // 是否开启捕捉辅助线
      guides: false
    });
    this.getMap().addControl(this._tool);
    this.eventTool.addEvents();
    this.enableSlice();
  }

  /**
   * 将绘制的图层移到地图最上层
   */
  moveGlDrawLayersToTop() {
    let layers = this.getMap().getStyle().layers;
    let customLayers = [];
    let glDrawLayers = [];
    layers.forEach((layer) => {
      if (layer.id.startsWith('gl-draw-custom')) {
        customLayers.push(layer);
      } else if (layer.id.startsWith('gl-draw')) {
        glDrawLayers.push(layer);
      }
    });
    customLayers.forEach((layer) => {
      this.getMap().moveLayer(layer.id);
    });
    glDrawLayers.forEach((layer) => {
      this.getMap().moveLayer(layer.id);
    });
  }

  /**
   * 编辑图形
   */
  editFeatures(features) {
    this._tool.set(turf.featureCollection(features));
    this.moveGlDrawLayersToTop();
  }

  /**
   * 切换编辑模式
   */
  changeMode(modename, opts) {
    this.eventSuffix = modename;
    this._tool.changeMode(modename, opts);
    this.moveGlDrawLayersToTop();
  }

  /**
   * 添加编辑模式
   * @param {*} mode 编辑模式
   */
  addMode(mode) {
    var { name, extend } = mode;
    if (extend) {
      var extendMode = this._tool.getAllModes()[extend];
      var newMode = {};
      for (let key in extendMode) {
        newMode[key] = extendMode[key];
      }
      for (let key in mode) {
        newMode[key] = mode[key];
      }
      this._tool.addMode({
        name,
        clazz: newMode
      });
    } else {
      this._tool.addMode({
        name,
        clazz: mode
      });
    }
  }


  /**
   * 重置编辑工具
   */
  reset() {
    this.snapUtil.stop();
    this._tool.changeMode('simple_select');
    setTimeout(() => {
      this._tool.set(turf.featureCollection([]));
    });
  }


  /**
   * 设置事件方法
   * @param {*} _events 事件方法
   */
  setEvents(_events) {
    for (let key in _events) {
      this.events[key] = _events[key];
    }
  }

  /**
   * 启用捕捉功能
   */
  enableSnap() {
    if (this._tool) {
      this.snapUtil.start();
      this._tool.options.snap = true;
      this._tool.options.snapOptions.snapFunction = this._defaultSnapFunction;
    }
  }

  /**
   * 禁用捕捉功能
   */
  disableSnap() {
    if (this._tool) {
      this.snapUtil.stop();
      this._tool.options.snap = true;
      this._tool.options.snapOptions.snapFunction = null;
    }
  }

  /**
   * 设置捕捉图形
   * @param {features} features 捕捉图形坐标
   * @param {*} filter 过滤条件：传入type:point或者type:linestring设置只捕捉点或者线
   */
  setSnapFeatures(features, filter) {
    this.snapUtil.initSnapSource(features, filter);
  }

  /**
   * 默认捕捉方法
   * @param {*} coords 当前鼠标位置坐标
   */
  defaultSnapFunction(coords) {
    var lngLat = this.snapUtil.snap({ lng: coords[0], lat: coords[1] });
    return {
      coord: [lngLat.lng, lngLat.lat],
      owner: lngLat.owner,
      ownerFeature: lngLat.ownerFeature
    };
  }

  /**
   * 开始切割
   * @param {feature} polygon 需要切割的图形
   */
  startSplit(polygon) {
    return new Promise((resolve) => {
      this.splitUtil.start(polygon).then((result) => {
        resolve(result);
      });
    });
  }

  enableSlice() {
    if(this._tool) {

      this._tool.options.sliceOptions.sliceFunction = SliceUtil2;
    }
  }

  /**
   * 停止切割
   */
  stopSplit() {
    this.splitUtil.stop();
  }

  /**
   * 编辑工具箱样式
   * @param {Object} style
   */
  setStyle(style) {
    // TODO
    console.log(style);
  }
  delete(featureIds) {
    this._tool.delete(featureIds);
  }
  deleteAll() {
    this._tool.deleteAll();
  }
  /**
   * 获取编辑图形
   */
  getAll() {
    return this._tool.getAll();
  }
  /**
   * 获取编辑模式
   */
  getMode() {
    return this._tool.getMode();
  }

  /**
   * 删除编辑图形
   */
  trash() {
    this._tool.trash();
  }
}

export default EditTool;
